//
//  JsonParser.m
//  Bus
//
//  Created by wangjiajia on 13-7-30.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "JsonParser.h"
#import "LoginResult.h"
#import "News.h"
#import "NewsInfo.h"
#import "Profit.h"
#import "RepDepInfo.h"
#import "RepDetail.h"
#import "RepTime.h"
#import "WFForm.h"
#import "UserForm.h"
#import "NSString+HTMLEncoding.h"
#import "ProcessResult.h"
#import "WorkFlowNode.h"
#import "NextStep.h"
#import "DepNode.h"
#import "People.h"
@implementation JsonParser


#pragma mark- 解析为登陆结果
+(LoginResult *)parseAsLoginResult:(NSString *)jsonResponse{
    NSDictionary *targetDict=[self getTargetDict:jsonResponse];
    
    // return  [[LoginResult alloc] initWithLoginRet:[[targetDict objectForKey:@"Ret"] intValue] andLoginMsg:[targetDict objectForKey:@"Info"]];//大小写铭感
    
    return [[LoginResult alloc] initWithLoginRet:[[targetDict objectForKey:@"Ret"] intValue] andLoginMsg:[targetDict objectForKey:@"Info"] andUserId:[[targetDict objectForKey:@"UserID"] intValue]andUserName:[targetDict objectForKey:@"UserName"]];
    
}

#pragma mark- 解析为新闻数组
+(NSMutableArray *)parseAsNews:(NSString *)jsonResponse{
    NSMutableArray* newsArray=[[NSMutableArray alloc] init];
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    //NSLog(@"%@",targetDict);
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        //NSLog(@"%@",item );
        //[newsArray addObject:item];//通过字典objectForKey可以取元素值，model.value也行，有必要转成model吗？
        
        News* news=[[News alloc] initWithParameters:[[item objectForKey:@"ArticleID"] intValue] andTitle:[item objectForKey:@"Title"] andSendTime:[item objectForKey:@"SendTime"] andSendUserName:[item objectForKey:@"SendUserName"]];
        [newsArray addObject:news];
        
    }
    //NSLog(@"%@",newsArray);
    
    return newsArray;
    
}

#pragma mark- 解析为新闻详情
+(NewsInfo *)parseAsNewsInfo:(NSString *)jsonResponse{
    NSDictionary* targetDict=[self getTargetHTMLDict:jsonResponse];
    
    return [[NewsInfo alloc] initWithParameters:[[targetDict objectForKey:@"ArticleID"]intValue ] andHits:[[targetDict objectForKey:@"Hits"]intValue ] andTitle:[targetDict objectForKey:@"Title"] andArticleCont:[targetDict objectForKey:@"ArticleCont"] andSendTime:[targetDict objectForKey:@"SendTime"] andSendUserName:[targetDict objectForKey:@"SendUserName"]];
}

#pragma mark- 解析为财务信息
+(NSMutableArray *)parseAsProfit:(NSString *)jsonResponse{
    NSMutableArray* profitArray=[[NSMutableArray alloc] initWithCapacity:10];
    
    NSDictionary* targetDict= [self getTargetDict:jsonResponse];
    //NSLog(@"财务targetDict:%@",targetDict);
    NSEnumerator* enumerator=   [targetDict objectEnumerator];
    NSDictionary* profitItem;
    while ((profitItem=enumerator.nextObject)) {
        //objectForKey 均是网络返回的字段
        //id->idNo;idesc->idesc;SumP->SumP;SumX->SumX;
        Profit* p=  [[Profit alloc] initWithParameters:[[profitItem objectForKey:@"id"]intValue ] andIdesc:[profitItem objectForKey:@"idesc"] andSumP:[profitItem objectForKey:@"SumP"]  andSumY:[profitItem objectForKey:@"SumY"] ];
        [profitArray addObject:p];
    }
    return profitArray;
}

#pragma mark- 解析为汇报时间列表
+(NSMutableArray *)parseAsRepTimeList:(NSString *)jsonResponse{
    
    NSMutableArray* repTimeArray=[[NSMutableArray alloc] initWithCapacity:12];
    
    NSDictionary* targetDict= [self getTargetDict:jsonResponse];
    
    //NSLog(@"时间targetDict:%@",targetDict);
    NSEnumerator* enumerator=   [targetDict objectEnumerator];
    NSDictionary* reptimeDict;
    while ((reptimeDict=enumerator.nextObject)) {
        RepTime* rt=[[RepTime alloc] initWithParameters:[reptimeDict objectForKey:@"RepTime"]andIsClicked:NO];
        [repTimeArray addObject:rt];//换用rt，是为了记住是否被点击过
        //[repTimeArray addObject:[reptimeDict objectForKey:@"RepTime"]];
    }
    return repTimeArray;
}

#pragma mark- 解析为汇报部门
+(NSMutableArray *)parseAsRepDepList:(NSString *)jsonResponse{
    
    NSMutableArray* repInfoArray=[[NSMutableArray alloc] initWithCapacity:12];
    
    NSDictionary* targetDict= [self getTargetDict:jsonResponse];
    
    //NSLog(@"时间targetDict:%@",targetDict);
    NSEnumerator* enumerator=   [targetDict objectEnumerator];
    NSDictionary* repInfoDict;
    while ((repInfoDict=enumerator.nextObject)) {
        RepDepInfo* rdi=[[RepDepInfo alloc] initWithParameters:[[repInfoDict objectForKey:@"RepID"] intValue] andRepDepName:[repInfoDict objectForKey:@"RepDep"]];
        [repInfoArray addObject:rdi];
    }
    return repInfoArray;
    
    
    
}

#pragma mark- 解析为汇报详情
+(RepDetail *)parseAsRepDetail:(NSString *)jsonResponse{
    NSDictionary* targetDict=[self getTargetHTMLDict:jsonResponse];
    
    return [[RepDetail alloc] initWithParameters:[targetDict objectForKey:@"ArticleCont"]  andRepDep:[targetDict objectForKey:@"RepDep"]  andRealTime:[targetDict objectForKey:@"RealTime"] ];
}



#pragma mark - 获取目标目录
+ (NSDictionary *)getTargetDict:(NSString *)jsonResponse {
    ////NSLog(@"解码前 %@",jsonResponse);
    ////jsonResponse= [jsonResponse HTMLDecoding];
    ////NSLog(@"解码后 %@",jsonResponse);
    
    NSDictionary *targetDict;
    NSError* error1;
    NSDictionary *rootDict=[NSJSONSerialization JSONObjectWithData:[  jsonResponse dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error1];//jsonResponse不能有任何乱码，否则解析为nil
    //NSLog(@"rootDict=%@",rootDict);
    if(error1){
        NSLog(@"1解析Json字符串发生错误:%@",error1 );
    }
    NSString * resultStr=[rootDict objectForKey:@"d"];
    //resultStr=[resultStr HTMLDecoding];
    //NSLog(@"字符串d=%@",resultStr);
    NSError* error2;
    if(nil==resultStr){
        //没有取到@“d”的值，说明为低版本的 .net2.0 / .net 3.0  返回格式为:{结果}
        targetDict=rootDict;
        
    }else{
        //取到@“d”的值resultStr,是字符串。如果为html，则在解析时候，不能有 " 可以有\r\n\t < >,在服务器端已经HTMLEncoding，没有了"影响(编码为&quot;),但是还存其他?的干扰。（<为&lt; >为&gt;）
        if([resultStr isEqualToString:@""]){
            resultStr=@"{}";
        }
        targetDict=[NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error2];
         //NSLog(@"targetDict=%@",targetDict);
    }
    if(error2){
        NSLog(@"解析Json字符串发生错误:%@",error2 );
    }
    return targetDict;
}

#pragma mark - 获取含有HTML字符串的“新闻”目标一个目录(IOS接口中，ArticleCont字段第一个返回)
+ (NSDictionary *)getTargetHTMLDict:(NSString *)jsonResponse {
    ////NSLog(@"解码前 %@\n",jsonResponse);
    ////jsonResponse= [jsonResponse HTMLDecoding];//调用了反而解析不了
    ////NSLog(@"解码后 %@\n",jsonResponse);
    NSDictionary *targetDict;
    
    NSDictionary *rootDict=[NSJSONSerialization JSONObjectWithData:[jsonResponse dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
    NSString * resultStr=[rootDict objectForKey:@"d"];
    //resultStr=[resultStr HTMLDecoding];
    //NSLog(@"\n rootDict=%@\n 字符串d=%@",rootDict,resultStr);
    NSError* error;
    if(nil==resultStr){
        //没有取到@“d”的值，说明为低版本的 .net2.0 / .net 3.0  返回格式为:{结果}
        targetDict=rootDict;
    }else{
        //resultStr如果为html，则在解析时候，不能有 " 可以有\r\n\t < >,在服务器端已经HTMLEncoding，没有了"影响(编码为&quot;),但是还存其他?的干扰。（<为&lt; >为&gt;）
        int point= [resultStr rangeOfString:@",\"ArticleID\""].location;
        //html页面内容单独截取出来
        NSString* preStr=[resultStr substringWithRange:NSMakeRange(16, point-17)];
        //剩余的Json内容
        NSString* restStr= [NSString stringWithFormat:@"{%@", [resultStr substringFromIndex:(point+1)]];
        
         //NSLog(@"\n presStr=%@",preStr);
         //NSLog(@"\n restStr=%@",restStr);
        
        targetDict=[NSJSONSerialization JSONObjectWithData:[restStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
        
        if(error){
            NSLog(@"解析Json字符串发生错误:%@",error );
        }else{
            NSMutableDictionary *finalDict=[NSMutableDictionary dictionaryWithDictionary:targetDict];
            //补上HTML,特殊字符串自动转义
            [finalDict setObject:preStr forKey:@"ArticleCont"];
            //NSLog(@"\n 包含HTML的Dict:>>>>>%@",finalDict);
            return finalDict;
        }
    }
    return targetDict;
}

#pragma mark - 获取含有HTML字符串的“表单”目标一个目录(IOS接口中，ArticleCont字段第一个返回)
+ (NSDictionary *)getTargetHTMLUserFormDict:(NSString *)jsonResponse {
    
    NSDictionary *targetDict;
    
    NSDictionary *rootDict=[NSJSONSerialization JSONObjectWithData:[jsonResponse dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];//解析得到的就是NSDictionary，如果硬要赋值给NSMutableDictionary也没事，但是一用setObject forKey 就奔溃。
    
    NSString * resultStr=[rootDict objectForKey:@"d"];
    //NSLog(@"字符串%@",resultStr);
    NSError* error;
    if(nil==resultStr){
        //没有取到@“d”的值，说明为低版本的 .net2.0 / .net 3.0  返回格式为:{结果}
        targetDict=rootDict;
    }else{
        //resultStr如果为html，则在解析时候，不能有 " 可以有\r\n\t < >,在服务器端已经HTMLEncoding，没有了"影响(编码为&quot;),但是还存其他?的干扰。（<为&lt; >为&gt;）
        int point= [resultStr rangeOfString:@",\"ArticleID\""].location;
        //html页面内容单独截取出来
        NSString* preStr=[resultStr substringWithRange:NSMakeRange(16, point-17)];
        //剩余的内容
        NSString* restStr= [NSString stringWithFormat:@"{%@", [resultStr substringFromIndex:(point+1)]];
        
        //NSLog(@"%@",preStr);
        //NSLog(@"%@",restStr);
        
        targetDict=[NSJSONSerialization JSONObjectWithData:[restStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
        
        NSMutableDictionary *finalDict=[NSMutableDictionary dictionaryWithDictionary:targetDict];
        //补上HTML
        [finalDict setObject:preStr forKey:@"FileContent"];
        //NSLog(@"包含HTML的Dict:>>>>>%@",finalDict);
        return finalDict;
    }
    if(error){
        NSLog(@"解析Json字符串发生错误:%@",error );
    }
    return targetDict;
}


#pragma mark- 解析为表单类型
+(NSMutableArray *)parseAsWFForm:(NSString *)jsonResponse{
    NSMutableArray* wfFormArray=[[NSMutableArray alloc] init];
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    //NSLog(@"%@",targetDict);
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        //自定义的 下拉列表的 数据源 必须是字符串 不能是对象
        //WFForm* wfForm=[[WFForm alloc] initWithParameters:[item objectForKey:@"FormName"]];
        //[wfFormArray addObject:wfform];
        [wfFormArray addObject:[item objectForKey:@"FormName"]];
    }
    //NSLog(@"%@",wfFormArray);
    
    return wfFormArray;
    
}
#pragma mark- 解析为新闻数组
+(NSMutableArray *)parseAsUserForms:(NSString *)jsonResponse{
    NSMutableArray* userFromArray=[[NSMutableArray alloc] init];
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    //NSLog(@"\n targetDict=%@",targetDict);
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        //NSLog(@"%@",item );
        UserForm* userForm=[UserForm initWithSequence:[item objectForKey:@"Sequence"] FormName:[item objectForKey:@"FormName"] Name:[item objectForKey:@"Name"] FqUserName:[item objectForKey:@"FqUserName"] State:[item objectForKey:@"State"] FileContent:[item objectForKey:@"FileContent"] NowTimes:[item objectForKey:@"NowTimes"] UpTimeSet:[item objectForKey:@"UpTimeSet"] WtUsername:[item objectForKey:@"WtUsername"] Id:[item objectForKey:@"Id"] UpNodeId:[item objectForKey:@"UpNodeId"] FlowNumber:[item objectForKey:@"FlowNumber"] FormId:[item objectForKey:@"FormId"] FormNumber:[item objectForKey:@"FormNumber"] JBRObjectId:[item objectForKey:@"JBRObjectId"] JBRObjectName:[item objectForKey:@"JBRObjectName"] SpModle:[item objectForKey:@"SpModle"] Number:[item objectForKey:@"Number"] FlowId:[item objectForKey:@"FlowId"] FlowName:[item objectForKey:@"FlowName"] UpNodeNumber:[item objectForKey:@"UpNodeNumber"] UpNodeNum:[item objectForKey:@"UpNodeNum"] UpNodeName:[item objectForKey:@"UpNodeName"] FqUserID:[item objectForKey:@"FqUserID"] YJBObjectId:[item objectForKey:@"YJBObjectId"] YJBObjecName:[item objectForKey:@"YJBObjecName"]];
        
        [userFromArray addObject:userForm];
        //NSLog(@"%@",userForm );
    }
    return userFromArray;
}

#pragma mark- 解析为单个新闻
+(UserForm *)parseAsUserForm:(NSString *)jsonResponse{
    
    NSDictionary* targetDict=[self getTargetHTMLUserFormDict:jsonResponse];
    //NSLog(@"\n targetDict=%@",targetDict);
    
    UserForm* userForm=[UserForm initWithSequence:[targetDict objectForKey:@"Sequence"] FormName:[targetDict objectForKey:@"FormName"] Name:[targetDict objectForKey:@"Name"] FqUserName:[targetDict objectForKey:@"FqUserName"] State:[targetDict objectForKey:@"State"] FileContent:[targetDict objectForKey:@"FileContent"] NowTimes:[targetDict objectForKey:@"NowTimes"] UpTimeSet:[targetDict objectForKey:@"UpTimeSet"] WtUsername:[targetDict objectForKey:@"WtUsername"] Id:[targetDict objectForKey:@"Id"] UpNodeId:[targetDict objectForKey:@"UpNodeId"] FlowNumber:[targetDict objectForKey:@"FlowNumber"] FormId:[targetDict objectForKey:@"FormId"] FormNumber:[targetDict objectForKey:@"FormNumber"] JBRObjectId:[targetDict objectForKey:@"JBRObjectId"] JBRObjectName:[targetDict objectForKey:@"JBRObjectName"] SpModle:[targetDict objectForKey:@"SpModle"] Number:[targetDict objectForKey:@"Number"] FlowId:[targetDict objectForKey:@"FlowId"] FlowName:[targetDict objectForKey:@"FlowName"] UpNodeNumber:[targetDict objectForKey:@"UpNodeNumber"] UpNodeNum:[targetDict objectForKey:@"UpNodeNum"] UpNodeName:[targetDict objectForKey:@"UpNodeName"] FqUserID:[targetDict objectForKey:@"FqUserID"] YJBObjectId:[targetDict objectForKey:@"YJBObjectId"] YJBObjecName:[targetDict objectForKey:@"YJBObjecName"]];
    return userForm;
}
#pragma mark- 解析只读列表
+(NSArray *)parseAsReadOnlyForm:(NSString *)jsonResponse{

    NSMutableArray* readOnlyFormArray=[[NSMutableArray alloc] init];
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    //NSLog(@"%@",targetDict);
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        [readOnlyFormArray addObject:[item objectForKey:@"FileNumber"]];
    }
     //NSLog(@"%@",readOnlyFormArray);
    return readOnlyFormArray;

}
#pragma mark- 解析处理结果
+(ProcessResult *)parseAsProcessResult:(NSString *)jsonResponse{
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    //NSLog(@"%@",targetDict);
    ProcessResult* pr=[[ProcessResult alloc] initWithResult:[[targetDict objectForKey:@"Result"] intValue] Msg:[targetDict objectForKey:@"Msg"]];
    return pr;

}
#pragma mark- 解析工作流节点
+(WorkFlowNode *)parseAsWorkFlowNode:(NSString *)jsonResponse{
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    //NSLog(@"%@",targetDict);
    WorkFlowNode* wfn=[[WorkFlowNode alloc]
                       initwithParams:[[targetDict objectForKey:@"ID"] intValue]
                       andNodeSite:[targetDict objectForKey:@"NodeSite"]
                       andSpChoice:[targetDict objectForKey:@"SpChoice"]
                       andJbrObjectId:[targetDict objectForKey:@"JBRObjectId"]
                       andJbrObjectName:[targetDict objectForKey:@"JBRObjectName"]
                       andJbbmObjectId:[targetDict objectForKey:@"JBBMObjectId"]
                       andJbbmObjectName:[targetDict objectForKey:@"JBBMObjectName"]
                       andJbjsObjectId:[targetDict objectForKey:@"JBJSObjectId"]
                       andJbjsObjectName:[targetDict objectForKey:@"JBJSObjectName"]];
    return wfn;
}

#pragma mark- 解析下一步骤
+(NSMutableArray *)parseAsNextStep:(NSString *)jsonResponse{
    NSMutableArray* nextSteps=[NSMutableArray arrayWithCapacity:5];
     NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        NextStep* nextStep=[[NextStep alloc] initwithParams:[[item objectForKey:@"ID"] intValue] andNodeName:[item objectForKey:@"NodeName"]];
        [nextSteps addObject:nextStep];
    }
    return nextSteps;
}
#pragma mark- 部门节点
+(NSMutableArray *)parseAsDepNode:(NSString *)jsonResponse{
    NSMutableArray* depNodes=[NSMutableArray arrayWithCapacity:5];
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        DepNode* depNode=[[DepNode alloc] initwithParams:[[item objectForKey:@"DepID"] intValue] andDepName:[item objectForKey:@"DepName"]];
        [depNodes addObject:depNode];
    }
    return depNodes;
}
#pragma mark- 人员
+(NSMutableArray *)parseAsPeoples:(NSString *)jsonResponse{
    NSMutableArray* peoples=[NSMutableArray arrayWithCapacity:5];
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    NSEnumerator* enumerator=  [targetDict objectEnumerator];
    NSDictionary * item;
    while( item=[enumerator nextObject]){
        People* people=[[People alloc]initwithParams:[[item objectForKey:@"UserID"] intValue]  andUserName:[item objectForKey:@"UserName"] ];
     
        [peoples addObject:people];
    }
    return peoples;
}

#pragma mark- 解析待办个数
+(NSString*)parseAsTotalNum:(NSString *)jsonResponse{
    
    NSDictionary* targetDict=[self getTargetDict:jsonResponse];
    return   (NSString*)[targetDict objectForKey:@"TotalNum"];
}
@end
